<template>
  <DefaultLayout>
    <div class="bg-gray-100 flex justify-center mx-40">
      <div class="w-full p-6 bg-white rounded-lg shadow-lg my-6">
        <div class="flex items-center mb-4">
          <div class="text-xl font-bold">
            <span> 剩余支付时间: &nbsp &nbsp </span><span class="text-red-600">{{ timer.minutes }} : {{ timer.seconds }} </span>
          </div>
        </div>
        <div class="border-t border-gray-300 my-2"></div>

        <div class="order_detail my-2">

          <div class="order_address">
            <div class="address_title">
              <span class="text-base font-bold">配送地址</span>
            </div>

            <div class="address_content flex">
              <div class="p-4 text-red-500 font-bold">
                寄送至
              </div>

              <div class="flex font-bold p-4">
                <span> {{ orderInfo.data.address.aProvinceName }} </span>
                <span> {{ orderInfo.data.address.aCityName }} </span>
                <span> {{ orderInfo.data.address.aDistrictName }} </span>
                <span> {{ orderInfo.data.address.aDetail }} </span>
              </div>

              <div class="flex font-bold p-4">
                <span>({{ orderInfo.data.oConsignee }})收</span>
                <span> {{ orderInfo.data.oPhone }} </span>
              </div>
            </div>
          </div>
          <div class="border-t border-gray-300 my-2"></div>

          <div class="order_goodsList">
            <div class="address_title">
              <span class="text-base font-bold">您的订单</span>
            </div>

            <table class="w-full mb-4">
              <thead>
                <tr class="text-left text-sm font-bold">
                  <th class="px-6 pt-6 pb-4">产品</th>
                  <th class="px-6 pt-6 pb-4 text-right">小计</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in orderInfo.data.orderGoodsList" :key="index" class="odd:bg-[#f7f8f8]">
                  <td class="px-6 py-4 flex items-center">
                    <img :src="item.goods.goodsPhoto" alt="产品图片" class="w-14 h-14 rounded-md object-cover mr-4">
                    <div>
                      <div class="font-semibold">{{ item.goods.goodsName }}</div>
                      <div class="text-red-500">× {{ item.cgNum }}</div>
                    </div>
                  </td>
                  <td class="px-6 py-4 text-right">¥{{ item.cgPrice }}</td>
                </tr> 
              </tbody>
            </table>

            <div class="flex justify-between font-semibold text-sm my-4 px-6">
              <span>小计</span>
              <span>¥{{ orderInfo.data.oTotalPrice }}</span>
            </div>
            <div class="border-t border-gray-300 my-2"></div>

            <div class="flex justify-between font-semibold text-sm my-4 px-6">
              <span>配送</span>
              <span>统一费率</span>
            </div>
            <div class="border-t border-gray-300 my-2"></div>

            <div class="flex justify-between font-semibold my-4 px-6 text-red-500">
              <span class="text-sm">合计</span>
              <span class="text-red-500 text-2xl">¥{{ orderInfo.data.oTotalPrice }}</span>
            </div>
          </div>
        </div>

        <div class="pay_button flex justify-end items-center mt-6 gap-6">
          <button class="text-red-600 border bg-[#fdf5f6] border-red-600 rounded-md py-1 px-4 hover:bg-opacity-75" @click="cancelOrder">取消</button>
          <button class="text-white bg-[#d0021b] rounded-md py-1 px-4 hover:bg-opacity-75" @click="payOrder">支付</button>
        </div>
      </div>
    </div>
  </DefaultLayout>
</template>

<script lang="ts" setup>
import { useUserStore } from "../store/user.ts";
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import DefaultLayout from '../layouts/DefaultLayout.vue';
import { getOrder } from "../apis/history.ts";
import { ElMessage } from "element-plus";
import * as PayApi from '../apis/PayPage.ts'

let intervalId;

const route = useRoute()
const router = useRouter();


const orderId = route.query.orderId

const timer = reactive({
  minutes: 0,
  seconds: 0,
  totalSec: 0
})

const orderInfo = reactive({ data: {} })

const getOrderData = async () => {
  const resp = await getOrder(orderId)
  console.log(resp, 'getOrderData');

  if (resp.code === 200) {
    orderInfo.data = resp.data;
    console.log(orderInfo.data)
    const timestamp = Date.parse(orderInfo.data.oOrderTime)
    const nowstamp = new Date().getTime()

    const totolSec = (timestamp - nowstamp + 60 * 1000 + 10000) / 1000

    timer.totalSec = totolSec
    timer.minutes = Math.floor(totolSec / 60);
    timer.seconds = Math.floor(totolSec % 60)

    intervalId = setInterval(() => {
      const total = Math.floor(timer.totalSec - 1)
      timer.totalSec = total
      timer.minutes = Math.floor(total / 60);
      timer.seconds = total % 60

      if (total < 0) {
        clearInterval(intervalId)
        timer.minutes = 0
        timer.seconds = 0
        ElMessage({
          type: 'warning',
          message: '订单已超时'
        })
        router.push({ name: 'UserInfo' })
      }
    }, 1000)
  }
}
getOrderData()

const payOrder = () => {
  console.log(orderInfo.data.oId);
  
  PayApi.payOrder(orderInfo.data.oId)
    .then(res => {
      console.log(res);
      if (res.code === 200) {
          ElMessage({
            message: '支付成功',
            type: 'success'
          })
        }
      router.push('/userinfo');
    })
    .catch(res => {
      console.log(res);
    })
  // if (countdownStore.orderStatus === 0) {
  //   try {
  //     const response = await axios.put(`/api/my-order/update/` + orderData.oid);
  //     console.log('PUT 请求成功:', response.data);
  //     // 可以根据需要处理响应数据或更新组件状态 
  //     countdownStore.orderStatus = 1;
  //     alert('支付成功！');
  //     if (intervalId !== null) {
  //       clearInterval(intervalId);
  //     }
  //     localStorage.removeItem('orderCreationTime');
  //     router.push('/');
  //   } catch (error) {
  //     console.error('支付失败:', error);
  //   }
  // } else {
  //   alert('订单已支付，无法重复操作。');
  // }
};

const cancelOrder = () => {
  PayApi.cancelOrder(orderInfo.data.oId)
    .then(res => {
      console.log(res);
      if (res.code === 200) {
          ElMessage({
            message: '订单取消',
            type: 'info'
          })
        }
      router.push('/userinfo');
    })
    .catch(res => {
      console.log(res);
    })
};

// const updateUser = async (userId: number) => {
//   try {
//     const response = await axios.put(`/api/users/${userId}`, newData);
//     console.log('PUT 请求成功:', response.data);
//     // 可以根据需要处理响应数据或更新组件状态
//   } catch (error) {
//     console.error('PUT 请求失败:', error);
//     // 可以根据需要处理错误，比如显示错误提示等
//   }
// };


</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
}

.order-info {
  margin-bottom: 20px;
}

.pay-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.status {
  font-size: 1.2rem;
  font-weight: bold;
}
</style>
